//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;

namespace CommunityServer.Blogs.Controls
{
	/// <summary>
	/// Displays a list of links for the curent blog
	/// </summary>
	public class LinkList : WeblogThemedControl
	{
		public LinkList()
		{
		}

		Repeater categories = null;

		public override void DataBind()
		{
			base.DataBind();

			categories.DataSource = LinkCategories.GetCategories( CurrentWeblog.SectionID, false, true, true);
			categories.DataBind();
		}

		/// <summary>
		/// Attach Repeater
		/// </summary>
		protected override void AttachChildControls()
		{
			categories = FindControl("Categories") as Repeater;
			categories.ItemCreated +=new RepeaterItemEventHandler(categories_ItemCreated);

			DataBind();
		}


		private void categories_ItemCreated(object sender, RepeaterItemEventArgs e)
		{
			switch ( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:
				case ListItemType.SelectedItem:

					LinkCategory lc = e.Item.DataItem as LinkCategory;

					IText catTitle = TextControlHelper.Create(e.Item.FindControl("CategoryTitle"));
					if(catTitle != null)
						catTitle.Text = lc.Name;

					Repeater links = e.Item.FindControl("Links") as Repeater;
					links.ItemCreated +=new RepeaterItemEventHandler(links_ItemCreated);
					links.DataSource = lc.Links;
					links.DataBind();

					break;
			}
		}

		private void links_ItemCreated(object sender, RepeaterItemEventArgs e)
		{
			switch ( e.Item.ItemType ) 
			{
				case ListItemType.Item:
				case ListItemType.AlternatingItem:
				case ListItemType.SelectedItem:

					Link link = e.Item.DataItem as Link;

					HyperLink hl = e.Item.FindControl("Link") as HyperLink;
					if (hl != null)
					{
						hl.Text = link.Title;
						hl.NavigateUrl = link.Url;
						if (!Globals.IsNullorEmpty(link.Rel))
							hl.Attributes.Add("rel", link.Rel);
					}

					Literal desc = e.Item.FindControl("Description") as Literal;
					if (desc != null)
					{
						if (!Globals.IsNullorEmpty(link.Description))
							desc.Text = link.Description;
						else
							desc.Visible = false;
					}

					break;
			}
		}
	}
}
